/*
 *@本JS功能：学生虚机分配详情
 *@本js作者：杨锡君
 *@编写时间：2017年11月17日
 */
$(function() {
	var Alert1 = new Alert();
	var confirm1 = new Confirm();
    var loading1 = new Loading();
    loading1.init();
	var $departNames = $("#departNames");
	var $tableBox = $(".tableList");
	var $searchBtn = $(".searchBtn");
	var $mb = $(".mb");
	var classesid = result.paramData.classId;
	var th = "<tr>" +
		"<th class=\"col-lg-1\">序号</th>" +
		"<th class=\"col-lg-2\">学生姓名</th>" +
		"<th class=\"col-lg-3\">班级</th>" +
		"<th class=\"col-lg-4\">分配类型</th>" +
		"<th class=\"col-lg-2\">操作</th>" +
		"</tr>";

	function tabelModel(opt, startRow) {
		var str =  "<tr data-num=\"0\">" +
			"<td class=\"col-lg-1\">" + startRow + "</td>" +
			"<td class=\"col-lg-2\" title=" + opt.userName + ">" + opt.userName + "</td>" +
			"<td class=\"col-lg-3\" title=" + opt.className + ">" + opt.className + "</td>" +
			"<td class=\"col-lg-4\" title=" + opt.templateType + ">" + opt.templateType + "</td>" +
			"<td class=\"col-lg-2\">";
		if(result.roleId != 2){
            str += "<a href=\"javascript:;\" title=\"分配虚机\"  data-stuorteaid=" + opt.stuorteaId + "  class=\"virAllocateBtn\">分配虚机</a>";
		}
		str += "<a class=\"virManaBtn\" data-name=" + opt.userName + " title=\"虚机管理\" data-stuorteaid=" + opt.stuorteaId + "  href=\"javascript:;\">虚机管理</a>" +
			"</td>" +
			"</tr>";
		return str;
	}

	function virManaBox(opt, name,id) {
		var str = "<div class=\"popup virMana\">" +
			"<div class=\"popup_box\">" +
			"<div class=\"popup_contenthead\"><b>" + name + "</b>.虚机管理<img class=\"popup_img\" src=\"pc/images/ico_alertDel.png\"></div>" +
			"<div class=\"popup_content\">" +
			"<table class=\"tableBox exchangeTable\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">" +
			"<tr>";
        if(result.roleId!=2){
            str+="<th><input type=\"checkbox\" name=\"controlAll\" id=\"controlAll\" class=\"allCheck\"></th>";
		}
        str+="<th>配置类型</th>" +
			"<th>虚机名称</th>" +
			"<th>IP地址</th>" +
			"<th>操作</th>" +
			"</tr>";
		var str1 = "";
		$.each(opt, function(key) {
			str1 += "<tr>";
			if(result.roleId!=2){
				str1 += "<td rowspan=" + this.serverList.length + "><input value=\"0\" data-templateid=" + this.templateId + " name=\"selecteds\" type=\"checkbox\" class=\"oneCheck\" /></td>";
			}
            str1 += "<td rowspan=" + this.serverList.length + ">" + this.templateName + "</td>";
			var n = 0;
			
			$.map(this.serverList, function(omg) {
				if(n = 0) {
					if(omg.isAvailable == 0) {
						str1 += "<td><img title=\""+ omg.errorMsg +"\"  src=\"pc/images/ico_errorCom.png\"/>";
					} else {
						if(omg.isMaster == 1) {
							str1 += "<td><img src=\"pc/images/ico_mainCom.png\"/>";
						} else {
							str1 += "<td><img src=\"pc/images/ico_slaveCom.png\"/>";
						}
					}
					str1 += omg.aliasName + "</td>" +
						"<td>" + omg.ip + "</td>" +
						"<td><a data-isavailable=" + omg.isAvailable + " data-id=" + omg.id + " href=\"javascript:;\" class=\"exchange\">替换</a></td>" +
						"</tr>";
					n++;
				} else {
						if(omg.isAvailable == 0) {
							str1 += "<td><img title=\""+ omg.errorMsg +"\" src=\"pc/images/ico_errorCom.png\"/>";
						} else {
							if(omg.isMaster == 1) {
								str1 += "<td><img src=\"pc/images/ico_mainCom.png\"/>";
							} else {
								str1 += "<td><img src=\"pc/images/ico_slaveCom.png\"/>";
							}
						}
					str1 += omg.aliasName + "</td>" +
						"<td>" + omg.ip + "</td>" +
						"<td><a data-isavailable=" + omg.isAvailable + " data-id=" + omg.id + " href=\"javascript:;\" class=\"exchange\">替换</a></td>" +
						"</tr>";
				}
			})

		});
        var str2 = "";
		if(result.roleId == 3 || result.roleId == 4){
            str2 = "</table>" +
                "</div>" +
                "<div class=\"popup_btn\">" +
                "<a data-stuorteaid="+ id +" class=\"popup_confirm cancelVirBtn publicBtn hover-btn\">解绑虚机</a>" +
                "<a data-stuorteaid="+ id +" class=\"popup_confirm delVirBtn publicBtn hover-btn\">删除虚机</a>" +
                "</div>" +
                "<div class=\"clear\"></div>" +
                "</div>" +
                "</div>";
		}

		return str + str1 + str2;
	}
	var exchangeModel = "<div class=\"popup exchangeBox\">"
						+"<div class=\"popup_box\">"
						+"<div class=\"popup_contenthead\">替换虚拟机<img class=\"popup_imgs\" src=\"pc/images/ico_alertDel.png\"></div>"
						+"<div class=\"popup_content\">"
						+"<div>故&emsp;&emsp;障:&ensp;<span data-sex=\"0\" class=\"male radioCheck\">是</span><span data-sex=\"1\"  class=\"female radio\">否</span></div>"
						+"<div class=\"inputRight\"><label for=\"departNames\">替换理由:&ensp;</label>"
						+"<input type=\"text\" class=\"exReason publicText\"  />"
						+"</div>"
						+"</div>"
						+"<div class=\"popup_btn\">"
						+"<a class=\"popup_confirm sureBtn  hover-btn\">确定</a>"
						+"<a class=\"notSureBtn publicCancleBtn\">取消</a>"
						+"</div>"
						+"<div class=\"clear\"></div>"
						+"</div>"
						+"</div>";
    function virConfigBox(opt) {
        var str = "<div class=\"popup\">" +
            "<div class=\"popup_box\">" +
            "<div class=\"popup_contenthead\">分配虚机<img class=\"popup_img\" src=\"pc/images/ico_alertDel.png\"></div>" +
            "<div class=\"popup_content\">" +
            "<div class=\"serverCountBox\">";
        var str1 = "";
        if(opt.serverCount.length != 0) {
            $.map(opt.serverCount, function(obj) {
                str1 += "<span class=\"fl\">" + obj.templateName + "：" + obj.serverCount + "</span>"
            });
        }
        var str2 = "<div class=\"clear\"></div></div>";
        var str3 = "";
        if(opt.template.length != 0) {
            $.map(opt.template, function(omg) {
                if(omg.isAvailable == 1) {
                    if(omg.isAllocate == 1){
                        str3 += "<div data-isavailable=" + omg.isAvailable + " data-isallocate=" + omg.isAllocate + " class=\"configBox\">" +
                            "<div class=\"configTitle\">" + omg.templateName + " <input data-templateid=" + omg.templateId + "  value=\"1\" checked=\"checked\"  name=\"selecteds\"  type=\"checkbox\" class=\"oneCheck\"/></div>";

                    }else{
                        str3 += "<div data-isavailable=" + omg.isAvailable + " data-isallocate=" + omg.isAllocate + " class=\"configBox\">" +
                            "<div class=\"configTitle\">" + omg.templateName + " <input data-templateid=" + omg.templateId + "  value=\"0\"  name=\"selecteds\"  type=\"checkbox\" class=\"oneCheck\"/></div>";

                    }
              	 } else {
                    str3 += "<div data-isavailable=" + omg.isAvailable + " data-isallocate=" + omg.isAllocate + "  class=\"configBoxs\">" +
                        "<div class=\"configTitle\">" + omg.templateName + "</div>";
                }
                $.each(omg.imageInfo, function(key) {
                    str3 += "<div class=\"imageName\">" + this + "</div>";
                });
                str3 += "</div>";
            });

        }

        var str4 = "</div>" +
            "<div class=\"popup_btn\">" +
            "<a class=\"popup_confirm exportBtn publicBtn hover-btn\">确定</a>" +
            "</div>" +
            "<div class=\"clear\"></div>" +
            "</div>" +
            "</div>";
        return str + str1 + str2 + str3 + str4;
    }
	var teaVirAllocation = {
		init: function() {
			this.bindEvent();
            maxLengthLimit.init("publicText");
		},
		bindEvent: function() {
			var self = this;
			var json = {
                "pageNum": 1,
                "pageSize": 10,
                "classId":classesid
			};
			if(result.roleId == 2){
				$(".looktg").attr("data-url","teacherClassManagement");
			}
			self.virBtnEvent();
			self.tabelList(json);
			$searchBtn.off("click").on("click", function() {
				var departNames = $departNames.val();
				var jsonStr = {
                    "pageNum": 1,
                    "pageSize": 10,
                    "classId":classesid
				};
				var flag = verification.spaceCode(departNames);
				var flags = verification.specialCode(departNames);
				if(flag != true) {
					Alert1.content = flag;
					$(".exReason").val("");
					Alert1.init();
					Alert1.show();
					return false;
				}
				if(flags != true) {
					Alert1.content = flags;
					$(".exReason").val("");
					Alert1.init();
					Alert1.show();
					return false;
				}
				if(departNames == "") {
                    departNames = "";
				} else {
					jsonStr.userName = departNames;
				}
				self.tabelList(jsonStr);
			});

		},
        virBtnEvent:function () {
			if(result.roleId != 2){
				$(".onBtn,.onImg,.offImg,.offBtn").remove();
			}else{
                $.ajax({
                    type: "get",
                    url: "server/status?classId="+classesid,
                    async: true,
                    success: function(msg) {
                        if(msg.code == "200"){
                            if(msg.data.code == 1){
                                $(".onBtn,.offBtn").show();
                                $(".onImg,.offImg").hide();
                            }else if(msg.data.code == 2){
                                $(".onImg").show();
                                $(".onBtn,.offImg,.offBtn").hide();
                            }else{
                                $(".offImg").show();
                                $(".onBtn,.onImg,.offBtn").hide();
                            }
                        }else{
                            Alert1.content = msg.message;
                            Alert1.init();
                            Alert1.show();
                        }
                    }
                });
                var timer = setInterval(function (args) {
                    $.ajax({
                        type: "get",
                        url: "server/status?classId="+classesid,
                        async: true,
                        success: function(msg) {
                            if(msg.code == "200"){
                                if(msg.data.code == 1){
                                    $(".onBtn,.offBtn").show();
                                    $(".onImg,.offImg").hide();
                                }else if(msg.data.code == 2){
                                    $(".onBtn").show();
                                    $(".onImg,.offImg,.offBtn").hide();
                                }else{
                                    $(".offImg").show();
                                    $(".onBtn,.onImg,.offBtn").hide();
                                }
                            }else{
                            	clearInterval(timer);
                                Alert1.content = msg.message;
                                Alert1.init();
                                Alert1.show();
                            }
                        }
                    });
				},5000);
				// 一键开启
				$(".onBtn").off("click").click(function() {
					var jsonStr = {
						"classId":classesid,
						"stuorteaId":result.stuorteaId
					};
					loading1.show();
                    $.ajax({
                        type: "post",
                        url: "server/start",
                        async: true,
						data:jsonStr,
                        success: function(msg) {
                        	loading1.hide();
							if(msg.code == "200"){
                                Alert1.content = "操作成功";
                                $(".onBtn,.offBtn,.offImg").hide();
                                $(".onImg").show();
                                Alert1.init();
                                Alert1.show();
							}else{
                                Alert1.content = msg.message;
                                Alert1.init();
                                Alert1.show();
							}
                        }
                    });
				});
                // 一键关闭
                $(".offBtn").off("click").click(function() {
                    var jsonStr = {
                        "classId":classesid,
                        "stuorteaId":result.stuorteaId
                    };
                    loading1.show();
                    $.ajax({
                        type: "post",
                        url: "server/stop",
                        async: true,
                        data:jsonStr,
                        success: function(msg) {
                            loading1.hide();
                            if(msg.code == "200"){
                                Alert1.content = "操作成功";
                                $(".onBtn,.offBtn,.onImg").hide();
                                $(".offImg").show();
                                Alert1.init();
                                Alert1.show();
                            }else{
                                Alert1.content = msg.message;
                                Alert1.init();
                                Alert1.show();
                            }
                        }
                    });
                });
			}

        },
		virManaEvent: function() {
			//			虚机管理
			var self = this;
			$(".virManaBtn").off("click").click(function() {
				$mb.show();
				var stuorteaid = $(this).attr("data-stuorteaid");
				var userName = $(this).attr("data-name");
				var id =  $(this).attr("data-stuorteaid");
				$.ajax({
					type: "get",
					url: "server/stuortea/"+id+"?classId="+classesid,
					async: true,
					success: function(msg) {
						if(msg.code == 200) {
							if($(".popup").length != 0) {
								$(".popup").remove();
							} else {
								var box = virManaBox(msg.data, userName,id);
								$("body").append(box);
								self.allCheckEvent();
								self.virManaBtnEvent();
							}
						} else {
							Alert1.content = msg.message;
							Alert1.init();
							Alert1.show();
						}
					}
				});
			});
		},
		exchangeSureEvent:function(id){
//			替换虚机确认
			var self = this;
			$(".sureBtn").off("click").click(function() {
				var errorMsg = $(".exReason").val();
				var isAvailable = Number($(".radioCheck").attr("data-sex"));
				var flag = verification.spaceCode(errorMsg);
				var flags = verification.specialCode(errorMsg);
                var url = "";
				if(errorMsg != ""){
                    if(flag != true) {
                        Alert1.content = flag;
                        $(".exReason").val("");
                        Alert1.init();
                        Alert1.show();
                        return false;
                    }
                    if(flags != true) {
                        Alert1.content = flags;
                        $(".exReason").val("");
                        Alert1.init();
                        Alert1.show();
                        return false;
                    }
                    url = "isAvailable="+isAvailable+"&errorMsg="+errorMsg;
				}else{
                    url = "isAvailable="+isAvailable;
				}
                // var jsonStr = {
                //     "errorMsg": errorMsg,
                //     "isAvailable": isAvailable
                // };
				loading1.show();
				$.ajax({
					type:"post",
					url:"server/allocate/replace/"+id+"?"+url,
					async:true,
					success:function(msg){
						loading1.hide();
						if(msg.code == 200){
							Alert1.content = "替换虚机成功";
							Alert1.success = function(){
								$(".popup").remove();
								$mb.hide();
								$(".masking").hide();
								var json = {
									"pageNum": 1,
									"pageSize": 10,
									"classId":classesid
								};
								self.tabelList(json);
								$departNames.val("");
							};
							Alert1.init();
							Alert1.show();
						}else{
							Alert1.content = msg.message;
							Alert1.init();
							Alert1.show();
						}
					}
				});
			});
			$(".popup_imgs").off("click").click(function() {
				$(".exchangeBox").remove();
				$(".masking").hide();
			});
			$(".notSureBtn").off("click").click(function() {
				$(".exchangeBox").remove();
				$(".masking").hide();
			});
		},
		virManaBtnEvent:function(){
			//替换 解绑 删除 X
			//替换
			var self = this;
			$(".exchange").off("click").click(function() {
				$(".masking").show();
				$("body").append(exchangeModel);
				var id = $(this).attr("data-id");
				//故障是否
				$(".male").off("click").on("click", function() {
				$(this).removeClass("radio").addClass("radioCheck");
				$(".female").removeClass("radioCheck").addClass("radio");
				});
				$(".female").off("click").on("click", function() {
					$(this).removeClass("radio").addClass("radioCheck");
					$(".male").removeClass("radioCheck").addClass("radio");
				});
				self.exchangeSureEvent(id);
			});
//			解绑
			$(".cancelVirBtn").off("click").click(function() {
				var stuorteaid = $(this).attr("data-stuorteaid");
				if($(".oneCheck[value=1]").length == 0) {
					Alert1.content = "请选择要解绑的虚机";
					Alert1.init();
					Alert1.show();
				} else {
					confirm1.content = "确定解绑这<a style=\"color:#c82011;text-decoration:underline;font-weight:bolder;\" href=\"javascript:;\">"+ $(".oneCheck[value=1]").length +"</a>个虚机集群吗"
					confirm1.success = function(){
						var arr = [];
						$.each($(".oneCheck[value=1]"), function(key) {
							arr.push(Number($(this).attr("data-templateid")));
						});
						var jsonStr = JSON.stringify(
							 arr
						);
						loading1.show();
						$.ajax({
							type:"put",
							url:"server/allocate/stuortea/"+stuorteaid+"?classId="+classesid,
                            contentType:"application/json;charset=utf-8",
							async:true,
							data:jsonStr,
							success:function(msg){
								loading1.hide();
								if(msg.code == 200){
									Alert1.content = "解绑虚机成功";
									Alert1.success = function() {
										$(".popup").remove();
										$mb.hide();
										var json = {
											"pageNum": 1,
											"pageSize": 10,
											"classId":classesid
										};
										self.tabelList(json);
										$departNames.val("");
									};
									Alert1.init();
									Alert1.show();
								}else{
									Alert1.content = msg.message;
									Alert1.init();
									Alert1.show();
								}
							}
						});
					};
					confirm1.init();
					confirm1.show();
				}
			});
			//删除
			$(".delVirBtn").off("click").click(function() {
				var stuorteaid = $(this).attr("data-stuorteaid");
				if($(".oneCheck[value=1]").length == 0) {
					Alert1.content = "请选择要删除的虚机";
					Alert1.init();
					Alert1.show();
				} else {
					confirm1.content = "确定删除这<a style=\"color:#c82011;text-decoration:underline;font-weight:bolder;\" href=\"javascript:;\">"+ $(".oneCheck[value=1]").length +"</a>个虚机集群吗"
					confirm1.success = function(){
						var arr = [];
						$.each($(".oneCheck[value=1]"), function(key) {
							arr.push(Number($(this).attr("data-templateid")));
						});
						var jsonStr = JSON.stringify(
							arr
						);
						loading1.show();
						$.ajax({
							type:"post",
							url:"server/allocate/delete/stuortea/"+stuorteaid+"?classId="+classesid,
							async:true,
                            contentType:"application/json;charset=utf-8",
							data:jsonStr,
							success:function(msg){
								loading1.hide();
								if(msg.code == 200){
									Alert1.content = "删除虚机成功";
									Alert1.success = function() {
										$(".popup").remove();
										$mb.hide();
										var json = {
                                            "pageNum": 1,
                                            "pageSize": 10,
                                            "classId":classesid
										};
										self.tabelList(json);
										$departNames.val("");
									};
									Alert1.init();
									Alert1.show();
								}else{
									Alert1.content = msg.failMsg;
									Alert1.init();
									Alert1.show();
								}
							}
						});
					};
					confirm1.init();
					confirm1.show();
				}
			});
			$(".popup_img").off("click").click(function() {
				$(".popup").remove();
				$mb.hide();
			});
		},
		allocateVirEvent: function() {
            //			分配虚机
            var self = this;
            $(".virAllocateBtn").off("click").click(function() {
                $mb.show();
                var stuorteaid = $(this).attr("data-stuorteaid");
                loading1.show();
                $.ajax({
                    type: "get",
                    url: "server/allocate/stuortea/" + stuorteaid+"?classId="+classesid,
                    async: true,
                    success: function(msg) {
                        loading1.hide();
                        if(msg.code == 200) {
                            if($(".popup").length != 0) {
                                $(".popup").remove();
                            } else {
                                var box = virConfigBox(msg.data);
                                $("body").append(box);
                                $(".oneCheck").change(function() {
                                    if($(this).val() == "0") {
                                        $(this).val("1");
                                    } else {
                                        $(this).val("0");
                                    }
                                });
                                self.allocateVirSubmit(stuorteaid);
                            }
                        } else {
                            Alert1.content = msg.message;
                            Alert1.init();
                            Alert1.show();
                        }
                    }
                });
            });
        },
        allocateVirSubmit: function(stuorteaid) {
            //			分配虚机提交及X
            var self = this;
            $(".exportBtn").off("click").click(function() {
                if($(".oneCheck[value=1]").length == 0) {
                    Alert1.content = "请选择要分配的虚机配置";
                    Alert1.init();
                    Alert1.show();
                } else {
                    var arr = [];
                    $.each($(".oneCheck[value=1]"), function(key) {
                        arr.push(Number($(this).attr("data-templateid")));
                    });
                    var jsonStr = JSON.stringify(
                        arr
                    );
                    loading1.show();
                    $.ajax({
                        type: "post",
                        url: " server/allocate/stuortea/" + stuorteaid+"?classId="+classesid,
                        contentType:"application/json;charset=utf-8",
                        async: true,
                        data:jsonStr ,
                        success: function(msg) {
                            loading1.hide();
                            if(msg.code == 200) {
                                Alert1.content = "分配虚机成功";
                                Alert1.success = function() {
                                    $(".popup").remove();
                                    $mb.hide();
                                    var json = {
                                        "pageNum": 1,
                                        "pageSize": 10,
                                        "classId":classesid
                                    };
                                    self.tabelList(json);
                                    $departNames.val("");
                                };
                                Alert1.init();
                                Alert1.show();
                            } else {
                                Alert1.content = msg.message;
                                Alert1.init();
                                Alert1.show();
                            }
                        }
                    });
                }
            });
            $(".popup_img").off("click").click(function() {
                $(".popup").remove();
                $mb.hide();
            });
        },
		tabelList: function(jsons) {
			var self = this;
			// json = JSON.stringify(jsons);
			loading1.show();
			$.ajax({
				type: "get",
				url: "server/allocate/student",
				data: jsons,
				async: true,
				success: function(msg) {
					loading1.hide();
					if(msg.code == 200) {
						$tableBox.empty();
						if(msg.data.list.length != 0) {
							//列表
							var tabel = "";
							var startRow = msg.data.startRow;
							$.map(msg.data.list, function(opt) {
								tabel += tabelModel(opt, startRow);
								startRow++;
							});
							$tableBox.append(th + tabel);
							self.virManaEvent();
                            self.allocateVirEvent();
						} else {
							var trImg = "<tr><td colspan='5'><img style='position:relative;margin: 80px auto 20px;' src='pc/images/ico_noneData.png'><p style='font-size:26px;color:#8a8a8a;width:100%;text-align:center;'>暂无数据</p></td></tr>";
							$tableBox.append(th + trImg)
						}
                        var sumpage = msg.data.pages;
                        if(sumpage == 0){
                            sumpage = 1;
                        }
                        var nowpage = 1;
                        var pagenumber = 10;
                        $(".tcdPageCode").createPage({
                            pageCount: sumpage, //总页数
                            current: nowpage, //当前页数
                            pageNumber: pagenumber, //每页显示数量
                            backFn: function(p) {
                                nowpage = p;
                                if(nowpage >= sumpage) {
                                    nowpage = sumpage;
                                }
                                var jsonStr = jsons;
                                jsonStr.pageNum = nowpage;
                                loading1.show();
                                $.ajax({
                                    type: "get",
                                    url: "server/allocate/student",
                                    data: jsonStr,
                                    async: true,
                                    success: function(msg) {
                                        //列表
                                        loading1.hide();
                                        $tableBox.empty();
                                        var tabel = "";
                                        var startRow = msg.data.startRow;
                                        $.map(msg.data.list, function(opt) {
                                            tabel += tabelModel(opt, startRow);
                                            startRow++;
                                        });
                                        $tableBox.append(th + tabel);
                                        self.virManaEvent();
                                        self.allocateVirEvent();
                                    }
                                });
                            }
                        });
					} else {
						Alert1.content = msg.message;
						Alert1.init();
						Alert1.show();
					}

				}
			});

		},
		allCheckEvent: function() {
			//全选
			allCheck.init("controlAll", "oneCheck");
		}
	};
	teaVirAllocation.init();
});
document.onkeydown = function(e) {
    var ev = document.all ? window.event : e;
    if(ev.keyCode == 13) {
        return false;
    }
};